import type { ToolCallResult } from "@shared/types/openai";
import { Settings } from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { ToolCallCard } from "./tool-call-card";

interface ToolCallsListProps {
  toolCalls: ToolCallResult[];
  threadId?: string;
  messageId?: string;
  className?: string;
}

export function ToolCallsList({
  toolCalls,
  threadId,
  messageId,
  className = "",
}: ToolCallsListProps) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const { t } = useTranslation();

  // Auto-collapse when all tool calls are completed
  useEffect(() => {
    const allCompleted = toolCalls.every(
      (tc) => tc.status === "success" || tc.status === "error",
    );
    if (allCompleted && toolCalls.length > 0) {
      // Auto-collapse after a short delay
      const timer = setTimeout(() => {
        setIsCollapsed(true);
      }, 2000);
      return () => clearTimeout(timer);
    }
    return undefined;
  }, [toolCalls]);

  if (!toolCalls || toolCalls.length === 0) {
    return null;
  }

  const pendingCount = toolCalls.filter((tc) => tc.status === "pending").length;
  const successCount = toolCalls.filter((tc) => tc.status === "success").length;
  const errorCount = toolCalls.filter((tc) => tc.status === "error").length;

  const getSummaryText = () => {
    if (pendingCount > 0) {
      return t("chat.tool-calls.labels.executing-tools", {
        count: pendingCount,
      });
    }

    const parts: string[] = [];
    if (successCount > 0)
      parts.push(
        t("chat.tool-calls.labels.success-count", { count: successCount }),
      );
    if (errorCount > 0)
      parts.push(
        t("chat.tool-calls.labels.error-count", { count: errorCount }),
      );

    return t("chat.tool-calls.labels.tools-completed", {
      summary: parts.join(", "),
    });
  };

  const getSummaryIcon = () => {
    if (pendingCount > 0) {
      return <Settings className="h-4 w-4 animate-spin text-blue-500" />;
    }
    if (errorCount > 0) {
      return <Settings className="h-4 w-4 text-red-500" />;
    }
    return <Settings className="h-4 w-4 text-green-500" />;
  };

  return (
    <div
      className={`rounded-lg border border-gray-200 bg-gray-50 ${className}`}
    >
      {/* Summary Header */}
      <button
        type="button"
        className="flex w-full cursor-pointer items-center justify-between p-3 transition-colors hover:bg-gray-100"
        onClick={() => setIsCollapsed(!isCollapsed)}
      >
        <div className="flex items-center space-x-2">
          {getSummaryIcon()}
          <span className="font-medium text-gray-700 text-sm">
            {getSummaryText()}
          </span>
          <span className="text-gray-500 text-xs">
            {t("chat.tool-calls.labels.tool-count", {
              count: toolCalls.length,
            })}
          </span>
        </div>

        <span className="text-gray-400 transition-colors hover:text-gray-600">
          <svg
            className={`h-4 w-4 transform transition-transform ${
              isCollapsed ? "rotate-0" : "rotate-180"
            }`}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            aria-hidden="true"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 9l-7 7-7-7"
            />
          </svg>
        </span>
      </button>

      {/* Tool Calls */}
      {!isCollapsed && (
        <div className="space-y-2 border-gray-200 border-t p-3">
          {toolCalls.map((toolCall) => (
            <ToolCallCard
              key={toolCall.id}
              toolCall={toolCall}
              threadId={threadId}
              messageId={messageId}
              className="shadow-sm"
            />
          ))}
        </div>
      )}
    </div>
  );
}
